/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package earleyalgorithm;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author NGOC
 */
public class Utility {
    public static boolean isTerminal(String word){
        if(word.charAt(0) > 97)
            return true;
        if(word.length() > 1) {
            if(word.charAt(1) > 97)
                return true;
            else
                return false;
        }
        return false;
    }
    public static ArrayList<String> readSentence(String path) throws FileNotFoundException, IOException{
        FileReader reader = new FileReader(path);
        Scanner scan = new Scanner(reader);
        scan.useDelimiter(" ");
        ArrayList result = new ArrayList<String>();
        while(scan.hasNext()){
            result.add(scan.next().toLowerCase());
        }
        reader.close();
        return result;
    }

    public static boolean isDictionary(String path, ArrayList sentence, WordCollection words) throws FileNotFoundException, IOException{
        boolean flag = false;
        for(int i = 0; i < sentence.size(); i++){
            flag = false;
            String word = (String)sentence.get(i);
            FileReader reader = new FileReader(path);
            Scanner scan = new Scanner(reader);
            while(scan.hasNextLine()){
                String[] src = scan.nextLine().split("\t");
                if(src[0].toLowerCase().equals(word)){
                    flag = true;
                    words.addWordClass(word, src[1].split(" "));
                    break;
                }
            }
            reader.close();
            if(!flag)
                return flag;
        }
        return flag;
    }

    public static Rule createRule(String line){
        String[] src = line.split("\t");
        Category left = new Category(src[0], Utility.isTerminal(src[0]));
        String[] srcRights = src[1].split(" ");
        Category[] rights = new Category[srcRights.length];
        for(int i = 0; i < rights.length; i++){
            rights[i] = new Category(srcRights[i], Utility.isTerminal(srcRights[i]));
        }
        return new Rule(left, rights);

    }

    public static Grammar readGrammar(String path) throws FileNotFoundException{
        Grammar result = null;
        FileReader reader = new FileReader(path);
        Scanner scan = new Scanner(reader);
        if(scan.hasNextLine()){
            Rule r = createRule(scan.nextLine());
            result = new Grammar("Grammar", r.getLeft());
            result.addRule(r);
        }
        while(scan.hasNextLine()){
            Rule r = createRule(scan.nextLine());
            result.addRule(r);
        }
        return result;
    }
}
